﻿using System.IO;
using System.Security.Cryptography;
using UnityEngine;

// Lua文件读取器
public class LuaFileReader
{
    private byte[] m_FileBuffer;
    private DPacket m_FileDPacket;

    // 加载指定文件
    public bool Load(string filename)
    {
        filename = Application.persistentDataPath + "/" + filename;
        // 判断文件是否存在
        if (!File.Exists(filename))
        {
            return false;
        }

        FileLoader loader = new FileLoader();
        if (!loader.Load(filename, FileLoader.FILE_MODE.TYPED_READ_ONLY))
        {
            loader.UnLoad();
            return false;
        }

        int len = (int)loader.Length();
        if (len <= 16)
        {
            loader.UnLoad();
            return false;
        }

        m_FileBuffer = new byte[len];
        if (loader.Read(ref m_FileBuffer, len) != len)
        {
            loader.UnLoad();
            return false;
        }

        // 计算buffer的MD5
        // 读取文件后进行文件MD5有效性校验
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] md5Data = md5.ComputeHash(m_FileBuffer, 0, m_FileBuffer.Length - 16);
        for (int i = 0; i < 16; i++)
        {
            if (md5Data[i] != m_FileBuffer[m_FileBuffer.Length - 16 + i])
            {
                md5.Clear();
                loader.UnLoad();
                return false;
            }
        }

        md5.Clear();
        m_FileDPacket = new DPacket(m_FileBuffer, len - 16);
        loader.UnLoad();
        return true;
    }

    // 读取Boolean
    public bool ReadBool()
    {
        if (m_FileDPacket == null) { return false; }
        if (m_FileDPacket.GetReadPos() + 1 > m_FileDPacket.Size())
        {
            return false;
        }
        return m_FileDPacket.ReadBool();
    }

    // 读取Int
    public int ReadInt()
    {
        if (m_FileDPacket == null)
        {
            return 0;
        }

        if (m_FileDPacket.GetReadPos() + 4 > m_FileDPacket.Size())
        {
            return 0;
        }
        return m_FileDPacket.ReadInt();
    }

    // 读取Float
    public float ReadFloat()
    {
        if (m_FileDPacket == null)
        {
            return 0.0f;
        }
        if (m_FileDPacket.GetReadPos() + 4 > m_FileDPacket.Size())
        {
            return 0.0f;
        }
        return m_FileDPacket.ReadFloat();
    }

    // 读取String
    public string ReadString()
    {
        if (m_FileDPacket == null)
        {
            return "";
        }
        return m_FileDPacket.ReadString();
    }

    // 清空操作
    public void Clear()
    {
        if (m_FileDPacket != null)
        {
            m_FileDPacket.Clear();
            m_FileDPacket = null;
        }
        if (m_FileBuffer != null)
        {
            m_FileBuffer = null;
        }
    }
}